package controllers

import (
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego/validation"
	"map/models"
	"time"
)

type CasesController struct {
	BaseController
}

func (this *CasesController) List() {
	page, err := this.GetInt("page")
	if err != nil {
		page = 1
	}
	limit, err := this.GetInt("limit")
	if err != nil {
		limit = 20
	}
	result, total := models.CasesList(page, limit)
	list := make([]map[string]interface{}, len(result))
	for key, value := range result {
		row := make(map[string]interface{})
		row["cases_id"] = value.Id
		row["number"] = value.Number
		row["type"] = value.Type
		row["crime_at"] = ""
		if !value.Crime_at.IsZero() {
			row["crime_at"] = value.Crime_at.Format("2006-01-01 15:04:05")
		}
		row["address"] = value.Address
		row["loss"] = value.Loss
		row["describe"] = value.Describe
		list[key] = row
	}
	listData := make(map[string]interface{})
	listData["cases_list"] = list
	listData["cases_total"] = total
	this.successData("", listData)
}

func (this *CasesController) Create() {
	valid := validation.Validation{}
	valid.Required(this.GetString("number"), "number").Message("请输入案件编号")
	valid.Required(this.GetString("type"), "type").Message("请选择案件类型")
	valid.Required(this.GetString("address"), "address").Message("请输入案发地址")
	valid.Required(this.GetString("crime_at"), "crime_at").Message("请输入案发时间")
	if valid.HasErrors() {
		for _, err := range valid.Errors {
			this.errors(err.Message, 1)
		}
	}

	Cases := new(models.Cases)
	Cases.Number = this.GetString("number")
	Cases.Type = this.GetString("type")
	Cases.Address = this.GetString("address")
	crime_at, _ := time.Parse("2006-01-02 15:04:05", this.GetString("crime_at"))
	Cases.Crime_at = crime_at
	Cases.Loss = this.GetString("loss")
	Cases.Describe = this.GetString("describe")
	orm.NewOrm().Insert(Cases)

	this.success("")
}

func (this *CasesController) Delete() {
	CasesId, _ := this.GetInt("cases_id")
	_, err := orm.NewOrm().Delete(&models.Cases{Id: CasesId})
	if err != nil {
		this.errors("删除失败", 1)
	}
	this.success("")
}
